package com.cskaoyan.mall.controller.admin;


import com.cskaoyan.mall.model.sql.Result;
import com.cskaoyan.mall.model.vo.AdminLoginVO;
import com.cskaoyan.mall.model.sql.Admin;
import com.cskaoyan.mall.service.AdminService;
import com.cskaoyan.mall.service.implement.AdminServiceImpl;
import com.cskaoyan.mall.model.bo.*;
import com.cskaoyan.mall.utils.HttpUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * User: zsquirrel
 * Date: 2020/4/28
 * Time: 4:00 下午
 */
@WebServlet("/api/admin/admin/*")
public class AdminServlet extends HttpServlet {

    private AdminService adminService = new AdminServiceImpl();

    Gson gson = new Gson();
/***********************************************    doPost   *******************************************************/
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //既然当前servlet可以处理诸如登录、查询所有Admin、删除Admin操作
        //那怎么知道当前请求是什么呢？
        //关键---> 有什么API可以区分不同的 url 呢  --> 利用URI 区分 URL
        String requestURI = request.getRequestURI();
        // login allAdmins...
        String action = requestURI.replace("/api/admin/admin/", ""); //用空字符串代替/api/admin/admin,从而得到 login
        // action --> "login"
        if("login".equals(action)){
            //这里区分了URI 之后，开始管理员登录的业务逻辑
           login(request, response);
        }else if("addAdminss".equals(action)){
            //这里开始新增管理员的业务逻辑
            addAdminss(request,response);
        }else if("updateAdminss".equals(action)){
            //这里开始更新管理员信息的业务逻辑
            updateAdminss(request,response);
        }else if("changePwd".equals(action)){
            changePwd(request,response);
        }else if("getSearchAdmins".equals(action)){
            getSearchAdmins(request,response);
        }
    }

    /**Request URL: http://localhost:8084/api/admin/admin/getSearchAdmins
     * {"nickname":"admin","email":"admin"}
     *  条件查询 admin 管理员账户信息
     *  1. 浏览器向 8084 数据服务器发送一个请求，请求体中携带了用户昵称参数 JSON
     *  2. 查询数据库，返回满足条件的数据
     *  3. 做出响应
     */
    private void getSearchAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        AdminSearchBO searchBO = gson.fromJson(requestBody, AdminSearchBO.class);
        List<Admin> admins = adminService.getSearchAdmins(searchBO);
        response.getWriter().println(gson.toJson(Result.ok(admins)));
    }



    /**
     *    Request URL: http://localhost:8084/api/admin/admin/changePwd
     *    请求参数：{adminToken: "379350689@qq.com", oldPwd: "fengfeng123", newPwd: "zhoukai!", confirmPwd: "zhoukai!"}
     *    从参数我们知道，需要建一个专门的类给它对应起来。取名为 ---> AdminChangePwdBO
     */
    private void changePwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request); //这一串就是JSON数据
        AdminChangePwdBO changePwdBO = gson.fromJson(requestBody, AdminChangePwdBO.class);
        Result result = adminService.changePwd(changePwdBO);
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 新增管理员逻辑
     *  ① 请求报文携带json参数
     *  ② 执行sql数据对admin表增加一行
     *  ③ 返回ok响应报文
     */
    private void addAdminss(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request); //这一串就是JSON数据拉
        AdminAddBO addBO = gson.fromJson(requestBody,AdminAddBO.class);
        //转到service调用层
        adminService.addAdminss(addBO);
        System.out.println(request.getContextPath());
        //response.setHeader("refresh","1;url=" + request.getContextPath() + "/api/admin/admin/allAdmins");
        response.getWriter().println(gson.toJson(Result.ok()));
    }

    /**
     * 管理员登录的具体业务逻辑
     * 1.抓包：抓请求报文（服务器上面、localhost）
     * 2.分析逻辑
     * 3.返回响应报文（响应体，格式是什么样的呢？抓包服务器）
     *
     * ① 浏览器向8084发送一个请求，请求体中携带了用户名密码参数（json字符串）
     * ② 查询数据库，校验当前用户名密码是否正确
     * ③ 根据结果返回不同的响应  200 ， 10000
     */
    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        AdminLoginBO loginBO = gson.fromJson(requestBody, AdminLoginBO.class);
        //System.out.println(loginBO);
        Admin login = adminService.login(loginBO);
        //对返回结果login （Admin.class）做出响应
        Result result = new Result();
        if(login !=null){
            request.getSession().setAttribute("admin",login);
            AdminLoginVO loginVO = new AdminLoginVO();
            System.out.println("Login:"+request.getMethod() + ":" + request.getRequestURI() +","+ request.getSession().getId());

            loginVO.setToken(login.getNickname());
            loginVO.setName(login.getNickname());
            response.getWriter().println(gson.toJson(Result.ok(loginVO)));
        }else{
            response.getWriter().println(gson.toJson(Result.error("密码错误---Feng提示")));
        }

    }

    /**
     * Request URL: http://localhost:8084/api/admin/admin/updateAdminss        保存修改按钮  POST
     * {id: 5, nickname: "Aayiae", email: "1548646879@qq.com", pwd: "dbsvesi21A!"}
     * @param request
     * @param response
     */
    private void updateAdminss(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        Admin changeBO = gson.fromJson(requestBody, Admin.class);//changeBO （有四个属性）
        adminService.updateAdminss(changeBO);

        //对返回对象change 进行响应 ， 肯定存在不为null
        response.getWriter().println(gson.toJson(Result.ok("修改成功！")));
    }

    /***********************************************    doGet   *******************************************************/
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/admin/", "");
        if("allAdmins".equals(action)){
            allAdmins(request, response);
        }else if("deleteAdmins".equals(action)){
            //这里开始删除管理员的业务逻辑
            deleteAdmins(request,response);
        }else if("getAdminsInfo".equals(action)){
            getAdminsInfo(request,response);
        }
    }

    /**
     * 传过来的数据是id=8,使用request.getParameter(id);
     */
    private void deleteAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        adminService.deleteAdmins(id);
        response.getWriter().println(gson.toJson(Result.ok("删除成功")));
    }

    /**
     * 展示所有的管理员信息
     * 1.抓包---没有请求参数
     * 2.分析逻辑
     * 3.抓包，响应体应该是什么
     *
     * ① 查询数据库，返回数据
     * ② 做出响应
     */
    private void allAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Admin> adminList = adminService.allAdmins();
        Result result = new Result();
        result.setCode(0);
        result.setData(adminList);
        response.getWriter().println(gson.toJson(result));
    }

    /**    Request URL: http://localhost:8084/api/admin/admin/getAdminsInfo?id=5   点击修改按钮  GET
     * 与delete同理，sql改变而已
     */
    private void getAdminsInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        Admin adminsInfo = adminService.getAdminsInfo(id);
        response.getWriter().println(gson.toJson(Result.ok(adminsInfo)));
    }
}
